import { defineStore } from 'pinia';

import { getDictionaryList } from '@/api/permission';

type dictionaryItem = {
  dictType: string;
  value: string | number;
  label: string;
  remark: string;
};

export const useDictionaryStore = defineStore('dictionary', {
  state: () => ({
    dictionaryList: [] as dictionaryItem[],
  }),
  getters: {},
  actions: {
    async getDictionaryList() {
      const res = await getDictionaryList();
      this.dictionaryList = res || [];
    },
    get(key: string, type = 'string' as 'string' | 'number') {
      const result: dictionaryItem[] = [];
      this.dictionaryList.forEach((item) => {
        if (item.dictType === key) {
          const value = { string: String(item.value), number: Number(item.value) }[type];
          result.push({ ...item, value });
        }
      });
      return result;
    },
    analysis(key: string, value: any) {
      value = value?.toString();
      if (!value) return '';
      const list = this.get(key);
      return list.find((item) => item.value === value)?.label || '';
    },
  },
});
